<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS实现购物车结算功能代码</title>
    <link rel="stylesheet" href="../css/style.css" />
    <link rel="stylesheet" href="https://at.alicdn.com/t/font_3246975_r7ow77w0bdn.css">
    <script src="../js/cookie.js"></script>
    <script src="../js/ajax.js"></script>
    <style>
        .w {
            width: 1226px;
            margin: 0 auto;
        }

        .header {
            background-color: #f5f5f5;
        }

        .header .header-nav {
            height: 40px;
            line-height: 40px;
            overflow: hidden;
        }

        .header .header-nav .header-nav-l,
        .header .header-nav .header-nav-r {
            font-size: 12px;
            display: flex;
        }

        .header .header-nav li {
            padding-right: 20px;
        }

        .header .header-nav .header-nav-l {
            float: left;
        }

        .header .header-nav .header-nav-r {
            float: right;
        }

        .header .header-nav .header-nav-l .hide {
            display: none;
        }

        .sign-tips a:first-child,
        .sign-user a:first-child {
            margin-right: 5px;
        }



        .header-nav-search {
            margin-top: 4px;
            float: left;
        }


        .header-nav-search .searchBar {
            width: 240px;
            height: 30px;
            border: 1px solid #dfdfdf;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #fff;
            margin-left: 200px;
        }

        .header-nav-search .searchBar .searchCon {
            border: none;
            width: 210px;
            text-indent: 5px;
            background-color: transparent;
        }

        .header-nav-search .searchBar .searchBtn {
            width: 30px;
            height: 30px;
            font-size: 20px;
            text-align: center;
            line-height: 30px;
            color: #dfdfdf;
        }

        .catbox .empty {
            /* width: 100%; */
            /* min-height: 400px; */
            text-align: center;
            background-color: #f5f5f5;
        }

        .catbox .empty .title {
            line-height: 30px;
        }
    </style>
</head>

<body>
    <div class="header">
        <div class="header-nav w">
            <ul class="header-nav-l">
                <li>湖北</li>
                <li class="sign-tips">
                    <a href="./login.html">亲,请登录</a>
                    <a href="./register.html">免费注册</a>
                </li>
                <li class="sign-user hide">
                    <a href="javascript:;" class="lg-user">欢迎您,xxx</a>
                    <a href="javascript:;" class="exit">退出登录</a>
                </li>
            </ul>
            <ul class="header-nav-search">
                <div class="searchBar">
                    <input type="text" class="searchCon">
                    <i class="iconfont icon-sousuo searchBtn"></i>
                </div>
            </ul>
            <ul class="header-nav-r">
                <li><a href="">我的淘宝</a></li>
                <li><a href="">购物车</a></li>
                <li><a href="">收藏夹</a></li>
            </ul>
        </div>
    </div>
    <div class="catbox">
        <!-- <div class="empty">
            <div class="title">您的购物车还是空的！</div>
            <div class="showImg">
                <img src="https://cdn.cnbj1.fds.api.mi-img.com/staticsfile/cart/cart-empty.png" alt="">
            </div>
        </div> -->
        <table id="cartTable">
            <thead>
                <tr>
                    <th><label>
                            <input class="check-all check" type="checkbox" />&nbsp;&nbsp;全选</label></th>
                    <th>商品</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/1.jpg" alt="" /><span>Casio/卡西欧 EX-TR350</span></td>
                    <td class="price">5999.88</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">5999.88</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/2.jpg" alt="" /><span>Canon/佳能 PowerShot SX50 HS</span></td>
                    <td class="price">3888.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">3888.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/3.jpg" alt="" /><span>Sony/索尼 DSC-WX300</span></td>
                    <td class="price">1428.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">1428.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/4.jpg" alt="" /><span>Fujifilm/富士 instax mini 25</span></td>
                    <td class="price">640.60</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">640.60</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr> -->
            </tbody>
        </table>
        <div class="foot" id="foot">

            <a class="fl" id="deleteAll" href="javascript:;">删除</a>
            <div class="fr closing" onclick="getTotal();">结 算</div>
            <input type="hidden" id="cartTotalPrice" />
            <div class="fr total">合计：￥<span id="priceTotal">0.00</span></div>
            <div class="fr selected" id="selected">已选商品<span id="selectedTotal">0</span>件<span
                    class="arrow up">︽</span><span class="arrow down">︾</span></div>
            <div class="selected-view">
                <div id="selectedViewList" class="clearfix">
                    <div><img src="../images/1.jpg"><span>取消选择</span></div>
                </div>
                <span class="arrow">◆<span>◆</span></span>
            </div>
        </div>
    </div>



</body>
<script>
    var catbox = document.getElementsByClassName("catbox")[0];

    var checkAll = document.getElementsByClassName("check-all")[0];
    var checkOneList = document.getElementsByClassName("check-one");

    var selectedTotal = document.getElementById("selectedTotal");
    var priceTotal = document.getElementById("priceTotal");

    var tbody = document.querySelector("#cartTable tbody");



    var signTips = document.getElementsByClassName("sign-tips")[0];
    var signUser = document.getElementsByClassName("sign-user")[0];
    var goodsList = document.getElementsByClassName("goods-list")[0];
    var searchCon = document.getElementsByClassName("searchCon")[0];
    var searchBtn = document.getElementsByClassName("searchBtn")[0];

    var lgc = getCookie("lgc");
    if (lgc) {
        signTips.classList.add("hide");
        signUser.classList.remove("hide");
        var lgUser = signUser.getElementsByClassName("lg-user")[0];
        var exit = signUser.getElementsByClassName("exit")[0];

        lgUser.textContent = `欢迎您,${lgc}`;
        exit.onclick = function () {
            deleteCookie("lgc");
            location.reload();
        }
    } else {
        location.href = "./login.html?ReturnUrl=" + encodeURIComponent(location.href);
    }


    searchBtn.onclick = function () {
        var wd = searchCon.value;
        location.href = "./search.html?wd=" + wd;
    }


    // 页面加载时 请求数据 渲染购物车


    ajax({
        type: "post",
        url: "http://43.138.81.225/demo/php/searchShoppingCarByUser.php",
        data: {
            user: lgc
        },
        dataType: "json",
        success: function (data) {
            console.log(data);
            var { status, message, list } = data;
            if (status) {
                if (list.length > 0) {
                    var html = "";
                    list.forEach(({ id, goodsId, goodsName, goodsMsg, goodsImg, goodsPrice, buyNum }) => {
                        // id => 购物车的数据编号(增删改需要使用) => 将id作为自定义属性绑定到tr中 => 每次获取id需通过tr
                        html += `<tr data-cid="${id}">
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods">
                        <img src="${goodsImg}" alt="" />
                        <span>${goodsName}</span>
                    </td>
                    <td class="price">${goodsPrice}</td>
                    <td class="count"><span class="reduce">${buyNum > 1 ? "-" : ""}</span>
                        <input class="count-input" type="text" value="${buyNum}" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">${(goodsPrice * buyNum).toFixed(2)}</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>`
                    })
                    tbody.innerHTML = html; // html结构放到页面 => 回流 =>生成结构
                } else {
                    catbox.innerHTML = ` <div class="empty">
                    <div class="title">您的购物车还是空的！</div>
                    <div class="showImg">
                        <img src="https://cdn.cnbj1.fds.api.mi-img.com/staticsfile/cart/cart-empty.png" alt="">
                    </div>
                </div>`;
                }
            } else {
                alert(message);
            }
        }
    })






    // 解决方法:
    // 1. 老赖行为  => 等数据请求成功 页面动态生成之后 再获取元素绑定事件
    // 2. 事件委托  => 给未来生成的元素绑定事件 (虽然你是未来生成的,到时点击时都会冒泡到父代元素) 

    catbox.addEventListener("click", shoppingCarHandler);

    function shoppingCarHandler(e) {
        // this -> 绑定事件的元素  catbox
        // target -> 触发事件的元素 事件源(可以是catbox子代元素中的每一个)
        var e = e || window.event;
        var target = e.target; //事件源(触发事件的元素)
        // console.log(11111);

        if (target.classList.contains("check-all")) {
            // console.log(target);
            checkAllHandler(target);
            getTotal();
        } else if (target.classList.contains("check-one")) {
            isAllChecked();
            getTotal();
        } else if (target.className == "add") {
            console.log(target);
            addHandler(target);
            getTotal();
        } else if (target.className == "reduce") {
            console.log(target);
            reduceHandler(target);
            getTotal();
        } else if (target.className == "delete") {
            console.log(target);
            deleteOneHandler(target);
            isAllChecked();
            getTotal();
        } else if (target.id == "deleteAll") {
            deleteAllHandler();
            isAllChecked();
            getTotal();
        }

    }











    function checkAllHandler(target) {
        var status = target.checked;
        console.log(status);
        for (var i = 0; i < checkOneList.length; i++) {
            var checkOne = checkOneList[i];
            checkOne.checked = status;
        }
    }

    function isAllChecked() {
        var flag = Array.from(checkOneList).every(function (item, index, array) {
            return item.checked == true;
        })
        // console.log(flag);
        checkAll.checked = checkOneList.length > 0 ? flag : false;
    }

    function addHandler(target) {
        // a. 输入框  数量 加一 
        var countInput = target.previousElementSibling;
        var num = countInput.value; // countInput的value值  num =  "1"
        num++;
        countInput.value = num;
        // countInput.value++;

        // b. 小计更新  =  单价*数量
        var countTd = target.parentElement.previousElementSibling;
        var subtotalTd = target.parentElement.nextElementSibling;

        // 注意:如果有单位  "5999.88元"  "¥5999.88"  => 处理(去单位)
        var price = countTd.textContent;

        var subtotal = price * num;

        subtotalTd.textContent = subtotal.toFixed(2);

        // 3. 减号按钮的 “-”  出现
        var reduce = countInput.previousElementSibling;
        reduce.textContent = "-";

        // 更新数据库
        var tr = target.parentElement.parentElement;
        var id = tr.dataset.cid;
        console.log(id);
        ajax({
            type: "post",
            url: "http://43.138.81.225/demo/php/updateShoppingCarById.php",
            data: {
                id: id,
                type: 1,  // 增加
                buyNum: 1, // 每次加一件
            },
            dataType: "json",
            // success: function (result) {
            //     console.log(result);
            // }
        })
    }

    function reduceHandler(target) {
        // a. 输入框  数量 减一 
        var countInput = target.nextElementSibling;
        var num = countInput.value;
        // c .减之前  判断  如果数量为1  不能减     return false
        if (num <= 1) { return false };

        num--; //自减

        //d. 减之后  判断  如果数量为1(2切为1)  减号按钮的 “-” 消失
        if (num <= 1) {
            target.textContent = "";
        }

        countInput.value = num;

        var countTd = target.parentElement.previousElementSibling;
        var subtotalTd = target.parentElement.nextElementSibling;

        // b. 小计更新
        // 注意:如果有单位  "5999.88元"  "¥5999.88"  => 处理(去单位)
        var price = countTd.textContent;

        var subtotal = price * num;

        subtotalTd.textContent = subtotal.toFixed(2);

        // 更新数据库
        var tr = target.parentElement.parentElement;
        var id = tr.dataset.cid;
        // console.log(id);
        ajax({
            type: "post",
            url: "http://43.138.81.225/demo/php/updateShoppingCarById.php",
            data: {
                id: id,
                type: 0,  // 增加
                buyNum: 1, // 每次加一件
            },
            dataType: "json",
            // success: function (result) {
            //     console.log(result);
            // }
        })
    }

    function deleteOneHandler(target) {
        if (confirm("是否删除该商品?")) {
            var tr = target.parentElement.parentElement;
            var id = tr.dataset.cid;
            // console.log(id);

            tr.remove();

            ajax({
                type: "get",
                url: "http://43.138.81.225/demo/php/deleteShoppingCarById.php",
                data: {
                    id: id,
                },
                dataType: "json",
                success: function (result) {
                    // console.log(result);
                    var { status, message } = result;
                    if (status) {
                        // tr.remove();  // 先删除数据 再删页面
                    } else {
                        alert(message);
                    }
                }
            })


        }
    }

    function deleteAllHandler() {


        // 找到所有选中状态的checkOne  => 对应获取id放到数组中
        var list = Array.from(checkOneList).filter((item) => item.checked).map(item => {
            var tr = item.parentElement.parentElement;
            var id = tr.dataset.cid;
            return id;
        })
        console.log(list);


        // 删除tr
        for (var j = 0; j < checkOneList.length; j++) {
            var checkOne = checkOneList[j];
            if (checkOne.checked) {
                var tr = checkOne.parentElement.parentElement;
                tr.remove();
                j--;
            }
        }


        ajax({
            type: "get",
            url: "http://43.138.81.225/demo/php/deleteShoppingCarById.php",
            data: {
                id: list.join(","),
            },
            dataType: "json",
            success: function (result) {
                // console.log(result);
                var { status, message } = result;
                if (status) {
                    // 先删除数据 再删页面
                    // for (var j = 0; j < checkOneList.length; j++) {
                    //     var checkOne = checkOneList[j];
                    //     if (checkOne.checked) {
                    //         var tr = checkOne.parentElement.parentElement;
                    //         tr.remove();
                    //         j--;
                    //     }
                    // }

                } else {
                    alert(message);
                }
            }
        })




    }

    function getTotal() {
        var sum = 0; // 被选中的商品的数量
        var allPrice = 0; // 被选中的商品的总价格

        // 找到所有选中状态的单选  => 通过它找到该商品对应的数量和小计  => 累加
        for (let j = 0; j < checkOneList.length; j++) {
            var item = checkOneList[j];
            if (item.checked) {
                var tr = item.parentElement.parentElement;  // 选中状态的单选 => tr
                var countInput = tr.getElementsByClassName("count-input")[0];
                var subtotalTd = tr.getElementsByClassName("subtotal")[0];
                // console.log(countInput, subtotalTd);

                var num = countInput.value * 1;
                var subtotal = subtotalTd.textContent * 1;

                sum += num;
                allPrice += subtotal;

            }
        }

        selectedTotal.textContent = sum;
        priceTotal.textContent = allPrice.toFixed(2);
    }
</script>

</html>